package com.ztgf.logistics.service.deppon;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.ztgf.common.constant.Result;
import com.ztgf.common.enums.CodeEnum;
import com.ztgf.common.utils.DateUtils;
import com.ztgf.common.utils.StrUtils;
import com.ztgf.dubbo.exception.ServiceException;
import com.ztgf.logistics.mapper.deppon.LogisticsOrderRemarkMapper;
import com.ztgf.logistics.models.bo.deppon.LogisticsOrderBO;
import com.ztgf.logistics.models.bo.deppon.LogisticsOrderEditBO;
import com.ztgf.logistics.models.bo.deppon.api.*;
import com.ztgf.logistics.models.dto.deppon.LogisticsBillDTO;
import com.ztgf.logistics.models.dto.deppon.LogisticsOrderRemarkDTO;
import com.ztgf.logistics.models.dto.deppon.LogisticsUserDTO;
import com.ztgf.logistics.models.service.deppon.ILogisticsBillService;
import com.ztgf.logistics.models.service.deppon.ILogisticsUserMoneyLogService;
import com.ztgf.logistics.models.service.deppon.ILogisticsUserService;
import com.ztgf.logistics.models.vo.ExportAdminLogisticsOrderListVO;
import com.ztgf.logistics.models.vo.ExportLogisticsOrderListVO;
import com.ztgf.logistics.models.vo.deppon.LogisticsOrderVO;
import com.ztgf.logistics.models.vo.deppon.api.*;
import com.ztgf.logistics.service.api.IDepponService;
import com.ztgf.order.models.bo.OrderAfterShipSaveBO;
import com.ztgf.order.models.bo.OrderShipSaveBO;
import com.ztgf.order.models.dto.OrderInvoiceDTO;
import com.ztgf.order.models.service.IOrderAfterShipService;
import com.ztgf.order.models.service.IOrderInvoiceService;
import com.ztgf.order.models.service.IOrderShipService;
import com.ztgf.sys.models.dto.SysInvoiceDTO;
import com.ztgf.sys.models.service.ISessionService;
import com.ztgf.sys.models.service.ISysInvoiceService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.BeanUtils;
import javax.annotation.Resource;

import com.ztgf.logistics.common.config.YmlConfig;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.ztgf.logistics.mapper.deppon.LogisticsOrderMapper;
import com.ztgf.logistics.models.service.deppon.ILogisticsOrderService;
import com.ztgf.logistics.models.bo.deppon.LogisticsOrderSaveBO;
import com.ztgf.logistics.models.dto.deppon.LogisticsOrderDTO;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 物流订单表控制器
 *
 * @author mxli
 * @Date 2021-09-13 22:15:56
 */
@DubboService
@Slf4j
public class LogisticsOrderServiceImpl extends ServiceImpl<LogisticsOrderMapper, LogisticsOrderDTO> implements ILogisticsOrderService{

    @Resource
    private YmlConfig ymlConfig;
    @Resource
    private LogisticsOrderRemarkMapper logisticsOrderRemarkMapper;
    @DubboReference
    private ISessionService sessionService;
    @Resource
    private IDepponService depponService;
    @DubboReference
    private IOrderInvoiceService orderInvoiceService;
    @DubboReference
    private IOrderShipService orderShipService;
    @DubboReference
    private IOrderAfterShipService orderAfterShipService;
    @DubboReference
    private ISysInvoiceService sysInvoiceService;
    @Resource
    private ILogisticsUserService logisticsUserService;
    @Resource
    private ILogisticsUserMoneyLogService logisticsUserMoneyLogService;
    @Resource
    private ILogisticsBillService logisticsBillService;
    @Value("${deppon-api.customer-code}")
    private String customerCode;
    @Value("${deppon-api.sign}")
    private String sign;
    @Override
    @Transactional(rollbackFor = ServiceException.class)
    public void add(LogisticsOrderSaveBO saveBO) {
        LogisticsOrderDTO dto = new LogisticsOrderDTO();
        BeanUtils.copyProperties(saveBO,dto);
        LogisticsOrderRemarkDTO remarkDTO = new LogisticsOrderRemarkDTO();
        BeanUtils.copyProperties(saveBO,remarkDTO);

        this.insert(dto);
        logisticsOrderRemarkMapper.insert(remarkDTO);
        //月结账单扣除预售金额
        if(dto.getType() == 1 && dto.getShopId().longValue() > 0){
            LogisticsUserDTO userDTO = logisticsUserService.selectById(dto.getShopId());
            if(!(userDTO.getType() == 1 || userDTO.getType() ==  2)){
                throw new ServiceException(CodeEnum.FAIL_DEPPON_400004);
            }
            if(userDTO.getStatus() == 1){
                throw new ServiceException(CodeEnum.FAIL_DEPPON_400005);
            }
            LogisticsUserDTO newUserDTO = new LogisticsUserDTO();
            BigDecimal moneyUsed = userDTO.getLogisticsMoneyUsed().add(dto.getTotalBudgetPrice());
            if(moneyUsed.compareTo(userDTO.getLogisticsMoneyQuota()) > 0){
                throw new ServiceException(CodeEnum.FAIL_DEPPON_400007);
            }

            //未支付的账单不能发月结单
            Wrapper wrapper = new EntityWrapper();
            wrapper.eq("shop_id", dto.getShopId());
            wrapper.ne("pay_status", 2);
            wrapper.last("limit 1");
            LogisticsBillDTO billDTO = logisticsBillService.selectOne(wrapper);
            if(billDTO != null){
                throw new ServiceException(CodeEnum.FAIL_DEPPON_400005);
            }
            newUserDTO.setLogisticsMoneyUsed(moneyUsed);
            newUserDTO.setLogisticsMoneyUnused(userDTO.getLogisticsMoneyQuota().subtract(newUserDTO.getLogisticsMoneyUsed()));
            newUserDTO.setLogisticsMoneyUsedScale(newUserDTO.getLogisticsMoneyUsed().divide(userDTO.getLogisticsMoneyQuota(), 4, BigDecimal.ROUND_HALF_UP).multiply(BigDecimal.valueOf(100)));
            logisticsUserService.updateMoney(dto.getId(),newUserDTO, userDTO, dto.getTotalBudgetPrice().negate(), 5, dto.getCreateUserId(), dto.getCreateUserName());
        }
    }

    @Override
    @Transactional
    public void updateMailNo(String logisticId, String mailNo, CodeEnum codeEnum) {

        Wrapper wrapper = new EntityWrapper();
        wrapper.eq("logistic_id", logisticId);
        LogisticsOrderDTO orderDTO = this.selectOne(wrapper);
        if(orderDTO == null){
            throw new ServiceException(codeEnum);
        }
        Long businessId = orderDTO.getBusinessId();
        if((businessId == null || businessId.equals(0L) && (orderDTO.getCustOrderNoType() == 1 || orderDTO.getCustOrderNoType() == 2 || orderDTO.getCustOrderNoType() == 3))){
            businessId = ymlConfig.getPkId();
        }
        LogisticsOrderRemarkDTO remarkDTO = logisticsOrderRemarkMapper.selectById(orderDTO.getId());
        LogisticsOrderDTO newOrderDTO = new LogisticsOrderDTO();
        newOrderDTO.setMailNo(mailNo);
        newOrderDTO.setBusinessId(businessId);
        if(!this.update(newOrderDTO, wrapper)){
            throw new ServiceException(codeEnum);
        }

        if(orderDTO.getCustOrderNoType() == 1){//订单
            OrderShipSaveBO shipSaveBO = new OrderShipSaveBO();
            //主键")
            shipSaveBO.setId(newOrderDTO.getBusinessId());
            //创建人")
            shipSaveBO.setCreateUserId(orderDTO.getCreateUserId());
            //订单id")
            shipSaveBO.setOrderId(orderDTO.getCustOrderId());
            //物流公司/送货员姓名")
            shipSaveBO.setLogisticsCompany("德邦快递");
            //物流公司编码")
            shipSaveBO.setCompanyCode("debangkuaidi");
            //物流单号")
            shipSaveBO.setShipmentNumber(mailNo);
            //联系方式")
//            shipSaveBO.setContactInformation();
            //发货方式 0全部发货，1部分发货")
            shipSaveBO.setShipWay(orderDTO.getSenderOrderType());
            //出发地")
            shipSaveBO.setDeparture(remarkDTO.getSenderProvince()+remarkDTO.getSenderCity()+remarkDTO.getSenderCounty()+remarkDTO.getSenderAddress());
            //目的地")
            shipSaveBO.setDestination(remarkDTO.getReceiverProvince()+remarkDTO.getReceiverCity()+remarkDTO.getReceiverCounty()+remarkDTO.getReceiverAddress());
            String mobile = remarkDTO.getReceiverMobile();
            if(StrUtils.isNotEmpty(mobile)){
                mobile = mobile.substring(6);
            }
            //买家手机号后四位")
            shipSaveBO.setLastFourPhoneNumber(mobile);
            //物流类型，0选择物流，1自己联系物流, 2德邦物流")
            shipSaveBO.setType(2);
            Result rs = orderShipService.addOrderShip(shipSaveBO);
            if(!rs.success()){
                throw new ServiceException(codeEnum);
            }

        } else if(orderDTO.getCustOrderNoType() == 2){//发票
            OrderInvoiceDTO invoiceDTO = new OrderInvoiceDTO();

            //物流类型,0选择物流,1自己联系物流")
            invoiceDTO.setLogisticsType(2);
            //物流公司名称/送货员姓名")
            invoiceDTO.setCompanyName("德邦快递");
            //"物流单号/送货员联系电话")
            invoiceDTO.setNumberPhone(mailNo);
            wrapper = new EntityWrapper();
            wrapper.eq("id", orderDTO.getBusinessId());
            if(!orderInvoiceService.update(invoiceDTO, wrapper)){
                throw new ServiceException(codeEnum);
            }
        } else if(orderDTO.getCustOrderNoType() == 3){//售后
            OrderAfterShipSaveBO bo = new OrderAfterShipSaveBO();
            //主键")
            bo.setId(newOrderDTO.getBusinessId());
            //创建人")
            bo.setCreateUserId(orderDTO.getCreateUserId());
            //订单id")
            bo.setOrderId(orderDTO.getCustOrderId());
            //物流公司/送货员姓名")
            bo.setLogisticsCompany("德邦快递");
            //物流公司编码")
            bo.setCompanyCode("debangkuaidi");
            //物流单号")
            bo.setShipmentNumber(mailNo);

            //发货方式 0全部发货，1部分发货")
            bo.setShipWay(orderDTO.getSenderOrderType());
            //出发地")
            bo.setDeparture(remarkDTO.getSenderProvince()+remarkDTO.getSenderCity()+remarkDTO.getSenderCounty()+remarkDTO.getSenderAddress());
            //目的地")
            bo.setDestination(remarkDTO.getReceiverProvince()+remarkDTO.getReceiverCity()+remarkDTO.getReceiverCounty()+remarkDTO.getReceiverAddress());
            //买家手机号后四位")
            String mobile = remarkDTO.getReceiverMobile();
            if(StrUtils.isNotEmpty(mobile)){
                mobile = mobile.substring(6);
            }
            bo.setLastFourPhoneNumber(mobile);
            //物流类型，0选择物流，1自己联系物流")
            bo.setType(2);
            //0买家，1卖家")
            bo.setUserType(orderDTO.getAfterSaleUserType());
            if(!orderAfterShipService.saveOrderShip(bo).success()){
                throw new ServiceException(codeEnum);
            }
        } else if(orderDTO.getCustOrderNoType() == 4){
            SysInvoiceDTO invoiceDTO = new SysInvoiceDTO();
            //物流类型,0选择物流,1自己联系物流")
            invoiceDTO.setLogisticsType(2);
            //物流公司名称/送货员姓名")
            invoiceDTO.setCompanyName("德邦快递");
            //物流单号/送货员联系电话")
            invoiceDTO.setNumberPhone(mailNo);

            wrapper = new EntityWrapper();
            wrapper.eq("id", orderDTO.getBusinessId());
            if(!sysInvoiceService.update(invoiceDTO, wrapper)){
                throw new ServiceException(codeEnum);
            }
        }

    }

    @Override
    public Result<LogisticsOrderVO> get(Long id) {
        return new Result<>(this.baseMapper.get(id));
    }

    @Override
    public Result<Page<LogisticsOrderVO>> queryPageList(LogisticsOrderBO bo) {
        Page<LogisticsOrderVO> page = new Page<>(bo.getPageNo(), bo.getPageSize());
        List<LogisticsOrderVO> list = this.baseMapper.queryPageList(page, bo);
        page.setRecords(list);
        return new Result<>(page);
    }

    @Override
    public Result update(LogisticsOrderEditBO saveBO) {
        LogisticsOrderDTO dto = this.selectById(saveBO.getId());
        LogisticsOrderRemarkDTO remarkDTO = logisticsOrderRemarkMapper.selectById(saveBO.getId());
        //ACCEPT：已受理；GOBACK：已退回
        if(dto == null || remarkDTO == null || !("ACCEPT".equalsIgnoreCase(dto.getStatusType()) || "GOBACK".equalsIgnoreCase(dto.getStatusType()))){
            return new Result(CodeEnum.FAIL_100008);
        }
        LogisticsOrderDTO newDTO = new LogisticsOrderDTO();
        BeanUtils.copyProperties(saveBO, newDTO);
        this.updateById(newDTO);
        LogisticsOrderRemarkDTO newRemarkDTO = new LogisticsOrderRemarkDTO();
        BeanUtils.copyProperties(saveBO, remarkDTO);
        logisticsOrderRemarkMapper.updateById(remarkDTO);

        DepponEditOrderBO editOrderBO = new DepponEditOrderBO();
        editOrderBO.setLogisticID(dto.getLogisticId());

        //发货人信息", required = true)
        DepponContactsBO sender = new DepponContactsBO();
        //发货人公司")
        sender.setCompanyName(saveBO.getSenderCompanyName());
        //发货部门编码")
        sender.setBusinessNetworkNo(saveBO.getSenderBusinessNetworkNo());
        //发货人手机", required = true)
        sender.setMobile(saveBO.getSenderMobile());
        //发货人电话")
        sender.setPhone(saveBO.getSenderPhone());
        //发货人省份", required = true)
        sender.setProvince(saveBO.getSenderProvince());
        //发货人城市", required = true)
        sender.setCity(saveBO.getSenderCity());
        //发货人区县", required = true)
        sender.setCounty(saveBO.getSenderCounty());
        //发货人乡镇街道")
        sender.setTown(saveBO.getSenderTown());
        //发货人详细地址", required = true)
        sender.setAddress(saveBO.getSenderAddress());
        editOrderBO.setSender(sender);
        DepponResultVO resultVO = depponService.updateOrder(editOrderBO);
        if(!resultVO.isResult()){
            return new Result(CodeEnum.FAIL_100008.getCode(), resultVO.getReason());
        }
        return new Result<>();
    }

    @Override
    @Transactional
    public Result saveCancel(Long id, String remark) {
        LogisticsOrderDTO dto = this.selectById(id);
        //ACCEPT：已受理  RECEIPTING：接货中； GOBACK：已退回；FAILGOT：揽货失败
        log.error("---------1------");
        if(dto == null || !("ACCEPT".equalsIgnoreCase(dto.getStatusType()) || "RECEIPTING".equalsIgnoreCase(dto.getStatusType())
                || "GOBACK".equalsIgnoreCase(dto.getStatusType()) || "FAILGOT".equalsIgnoreCase(dto.getStatusType())
            || "GOT".equalsIgnoreCase(dto.getStatusType()))){
            log.error("---------2------");
            return new Result(CodeEnum.FAIL_100059);
        }
        LogisticsOrderDTO newDTO = new LogisticsOrderDTO();
        newDTO.setId(id);
        newDTO.setStatusType("CANCEL");
        newDTO.setComments(remark);
        //月结账单扣除预售金额
        if(dto.getType() == 1 && dto.getShopId().longValue() > 0){
            log.error("---------3------");
            saveCancleMoney(newDTO, dto);
        }
        if(updateById(newDTO)){
            log.error("---------4------");
            if(dto.getCustOrderNoType() == 1){
                //清空运单号
                Wrapper wrapper = new EntityWrapper();
                wrapper.eq("id", dto.getBusinessId());
                wrapper.eq("shipment_number", dto.getMailNo());
                orderShipService.delete(wrapper);
            } else if(dto.getCustOrderNoType() == 2){
                //删除数据
                OrderInvoiceDTO invoiceDTO = new OrderInvoiceDTO();

                //物流类型,0选择物流,1自己联系物流")
                invoiceDTO.setLogisticsType(2);
                //物流公司名称/送货员姓名")
                invoiceDTO.setCompanyName("");
                //"物流单号/送货员联系电话")
                invoiceDTO.setNumberPhone("");
                Wrapper wrapper = new EntityWrapper();
                wrapper.eq("id", dto.getBusinessId());
                wrapper.eq("number_phone", dto.getMailNo());
                orderInvoiceService.update(invoiceDTO, wrapper);
            } else if(dto.getCustOrderNoType() == 2){
                //清空运单号
                Wrapper wrapper = new EntityWrapper();
                wrapper.eq("id", dto.getBusinessId());
                wrapper.eq("shipment_number", dto.getMailNo());
                orderAfterShipService.delete(wrapper);
            } else if(dto.getCustOrderNoType() == 3){//售后
                //清空运单号
                Wrapper wrapper = new EntityWrapper();
                wrapper.eq("id", dto.getBusinessId());
                wrapper.eq("shipment_number", dto.getMailNo());
                orderAfterShipService.delete(wrapper);
            } else if(dto.getCustOrderNoType() == 4){
                SysInvoiceDTO invoiceDTO = new SysInvoiceDTO();
                //物流类型,0选择物流,1自己联系物流")
                invoiceDTO.setLogisticsType(2);
                //物流公司名称/送货员姓名")
                invoiceDTO.setCompanyName("");
                //物流单号/送货员联系电话")
                invoiceDTO.setNumberPhone("");
                Wrapper wrapper = new EntityWrapper();
                wrapper.eq("id", dto.getBusinessId());
                wrapper.eq("number_phone", dto.getMailNo());
                sysInvoiceService.update(invoiceDTO, wrapper);

            }

            if(StrUtils.isNotEmpty(dto.getMailNo())){
                DepponCancleBO cancleBO = new DepponCancleBO();
                //渠道单号", required = true)
                cancleBO.setLogisticID(dto.getLogisticId());
                //运单号", required = true)
                cancleBO.setMailNo(dto.getMailNo());
                //撤销时间", required = true)
                cancleBO.setCancelTime(DateUtils.getCurrentDateTimeStr());
                //撤销备注", required = true)
                cancleBO.setRemark(remark);
                DepponResultVO resultVO = depponService.saveCancleOrder(cancleBO);
                if(!resultVO.isResult()){
                    throw new ServiceException(CodeEnum.FAIL_100008.getCode(), resultVO.getReason());
                }
            }
            return new Result<>();
        } else {
            throw new ServiceException(CodeEnum.FAIL_100059);
        }
    }

    @Override
    public List<ExportLogisticsOrderListVO> queryExportList(String ids) {
        List<ExportLogisticsOrderListVO> list = new ArrayList<>();
        if (ids != null) {
        String[] split = ids.split(",");
        for (String id : split) {
            LogisticsOrderVO vo = this.baseMapper.get(Long.valueOf(id));
            if (vo != null) {
                ExportLogisticsOrderListVO exportLogisticsOrderListVO = new ExportLogisticsOrderListVO();
                exportLogisticsOrderListVO.setLogisticId(vo.getLogisticId());
                exportLogisticsOrderListVO.setMailNo(vo.getMailNo());
                if (vo.getUpdateTime() != null) {
                    exportLogisticsOrderListVO.setUpdateTime(DateUtils.dateToStr(vo.getUpdateTime(), DateUtils.DATE_FORMAT_DATETIME));
                }
                if (vo.getType().equals(0)) {
                    exportLogisticsOrderListVO.setType("现结");
                }
                if (vo.getType().equals(1)) {
                    exportLogisticsOrderListVO.setType("月结");
                }
                if (vo.getTotalPrice() != null) {
                    exportLogisticsOrderListVO.setTransportPrice(vo.getTotalPrice().setScale(2, BigDecimal.ROUND_UP));
                } else {
                    exportLogisticsOrderListVO.setTransportPrice(new BigDecimal(0.00).setScale(2, BigDecimal.ROUND_UP));
                }

                exportLogisticsOrderListVO.setCustOrderNo(vo.getCustOrderNo());
                exportLogisticsOrderListVO.setReceiverName(vo.getReceiverName());
                exportLogisticsOrderListVO.setSenderName(vo.getSenderName());
                exportLogisticsOrderListVO.setShopName(vo.getShopName());
                exportLogisticsOrderListVO.setCargoName(vo.getCargoName());
                if (vo.getTotalWeight() != null) {
                    exportLogisticsOrderListVO.setTotalWeight(vo.getTotalWeight().setScale(2, BigDecimal.ROUND_UP));
                } else {
                    exportLogisticsOrderListVO.setTotalWeight(new BigDecimal(0.00).setScale(2, BigDecimal.ROUND_UP));
                }
                exportLogisticsOrderListVO.setTotalNumber(vo.getTotalNumber());
                exportLogisticsOrderListVO.setDepartureStation(vo.getSenderProvince() + "-" + vo.getSenderCity() + "-" + vo.getSenderCounty() + "-" + vo.getSenderAddress());
                exportLogisticsOrderListVO.setDestination(vo.getReceiverProvince() + "-" + vo.getReceiverCity() + "-" + vo.getReceiverCounty() + "-" + vo.getReceiverAddress());
                list.add(exportLogisticsOrderListVO);
            }

        }
    }
        if (list==null){
            ExportLogisticsOrderListVO exportLogisticsOrderListVO = new ExportLogisticsOrderListVO();
            list.add(exportLogisticsOrderListVO);
        }
        return list;
    }

    @Override
    public List<ExportAdminLogisticsOrderListVO> queryAdminExportList(String ids) {
        List<ExportAdminLogisticsOrderListVO> list = new ArrayList<>();
        if (ids != null) {
            String[] split = ids.split(",");
            for (String id : split) {
                LogisticsOrderVO vo = this.baseMapper.get(Long.valueOf(id));
                if (vo != null) {
                    ExportAdminLogisticsOrderListVO exportAdminLogisticsOrderListVO = new ExportAdminLogisticsOrderListVO();
                    exportAdminLogisticsOrderListVO.setLogisticId(vo.getLogisticId());
                    exportAdminLogisticsOrderListVO.setMailNo(vo.getMailNo());
                    if (vo.getUpdateTime() != null) {
                        exportAdminLogisticsOrderListVO.setUpdateTime(DateUtils.dateToStr(vo.getUpdateTime(), DateUtils.DATE_FORMAT_DATETIME));
                    }
                    if (vo.getType().equals(0)) {
                        exportAdminLogisticsOrderListVO.setType("现结");
                    }
                    if (vo.getType().equals(1)) {
                        exportAdminLogisticsOrderListVO.setType("月结");
                    }
                    if (vo.getTotalPrice() != null) {
                        exportAdminLogisticsOrderListVO.setTransportPrice(vo.getTotalPrice().setScale(2, BigDecimal.ROUND_UP));
                    } else {
                        exportAdminLogisticsOrderListVO.setTransportPrice(new BigDecimal(0.00).setScale(2, BigDecimal.ROUND_UP));
                    }

                    exportAdminLogisticsOrderListVO.setStatusType(logisticsStatusTransition(vo.getStatusType(),vo.getComments()));//设置物流状态
                    exportAdminLogisticsOrderListVO.setCustOrderNo(vo.getCustOrderNo());
                    exportAdminLogisticsOrderListVO.setReceiverName(vo.getReceiverName());
                    exportAdminLogisticsOrderListVO.setSenderName(vo.getSenderName());
                    if(StringUtils.isEmpty(vo.getShopName())){
                        exportAdminLogisticsOrderListVO.setShopName(vo.getCreateUserName());
                    }else{
                        exportAdminLogisticsOrderListVO.setShopName(vo.getShopName());
                    }

                    exportAdminLogisticsOrderListVO.setCargoName(vo.getCargoName());
                    if (vo.getTotalWeight() != null) {
                        exportAdminLogisticsOrderListVO.setTotalWeight(vo.getTotalWeight().setScale(2, BigDecimal.ROUND_UP));
                    } else {
                        exportAdminLogisticsOrderListVO.setTotalWeight(new BigDecimal(0.00).setScale(2, BigDecimal.ROUND_UP));
                    }
                    exportAdminLogisticsOrderListVO.setTotalNumber(vo.getTotalNumber());
                    exportAdminLogisticsOrderListVO.setDepartureStation(vo.getSenderProvince() + "-" + vo.getSenderCity() + "-" + vo.getSenderCounty() + "-" + vo.getSenderAddress());
                    exportAdminLogisticsOrderListVO.setDestination(vo.getReceiverProvince() + "-" + vo.getReceiverCity() + "-" + vo.getReceiverCounty() + "-" + vo.getReceiverAddress());
                    list.add(exportAdminLogisticsOrderListVO);
                }

            }
        }
        if (list==null){
            ExportAdminLogisticsOrderListVO exportAdminLogisticsOrderListVO = new ExportAdminLogisticsOrderListVO();
            list.add(exportAdminLogisticsOrderListVO);
        }
        return list;
    }

    //物流状态转换
    private  String logisticsStatusTransition(String statusType,String comments){
         String statusReason = "";
         if(statusType.equalsIgnoreCase("CANCEL")){
             statusReason = "已取消";
         }else if(statusType.equalsIgnoreCase("FAILGOT")){
             statusReason = "揽货失败";
         }else if(statusType.equalsIgnoreCase("GOBACK")){
             statusReason = "已退回";
         }else if(statusType.equalsIgnoreCase("GOT")){
             statusReason = "已开单";
         }else if(statusType.equalsIgnoreCase("INVALID")){
             statusReason = "已作废";
         }else if(statusType.equalsIgnoreCase("RECEIPTING")){
             statusReason = comments;
         }else if(statusType.equalsIgnoreCase("REJECT")){
             statusReason = "已拒绝";
         }else if(statusType.equalsIgnoreCase("SHOUTCAR")){
             statusReason = "已约车";
         }else if(statusType.equalsIgnoreCase("SIGNFAILED")){
             statusReason = "异常签收";
         }else if(statusType.equalsIgnoreCase("SIGNSUCCESS")){
             statusReason = "正常签收";
         }else if(statusType.equalsIgnoreCase("ACCEPT")){
             statusReason = "已受理";
         }

         return statusReason;
    }

//    @Override
//    public List<ExportAdminLogisticsOrderListVO> queryAdminExportList(String ids) {
//        String[] split = ids.split(",");
//        List<ExportAdminLogisticsOrderListVO> list=new ArrayList<>();
//        for (String id : split) {
//            LogisticsOrderVO vo= this.baseMapper.queryPageListByExport(Long.valueOf(id));
//            ExportAdminLogisticsOrderListVO exportLogisticsOrderListVO = new ExportAdminLogisticsOrderListVO();
//            exportLogisticsOrderListVO.setLogisticId(vo.getLogisticId());
//            exportLogisticsOrderListVO.setMailNo(vo.getMailNo());
//            if (vo.getUpdateTime()!=null){
//                exportLogisticsOrderListVO.setUpdateTime(DateUtils.dateToStr(vo.getUpdateTime(), DateUtils.DATE_FORMAT_DATETIME));
//            }
//            if (vo.getType().equals(0)){
//                exportLogisticsOrderListVO.setType("现结");
//            }
//            if (vo.getType().equals(1)){
//                exportLogisticsOrderListVO.setType("月结");
//            }
//            if(vo.getTotalPrice()!=null){
//                exportLogisticsOrderListVO.setTransportPrice(vo.getTotalPrice().setScale(2, BigDecimal.ROUND_UP));
//            }else {
//                exportLogisticsOrderListVO.setTransportPrice(new BigDecimal(0.00).setScale(2, BigDecimal.ROUND_UP));
//            }
//           // exportLogisticsOrderListVO.setCustOrderNo(vo.getCustOrderNo());
//            exportLogisticsOrderListVO.setReceiverName(vo.getReceiverName());
//            exportLogisticsOrderListVO.setSenderName(vo.getSenderName());
//            list.add(exportLogisticsOrderListVO);
//        }
//
//        return list;
//    }

    @Override
    public Result<DepponWebsiteListVO> queryWebsiteList(DepponWebsiteBO bo) {
        DepponResultVO<DepponWebsiteListVO> resultVO =  depponService.queryWebsiteList(bo);
        if(resultVO.isResult()){
            return new Result<>(resultVO.getResponseParam());
        } else {
            return new Result(CodeEnum.FAIL, resultVO.getReason());
        }

    }

    @Override
    public Result<List<DepponBudgetVO>> saveBudget(DepponBudgetBO bo) {
        DepponResultVO<List<DepponBudgetVO>> resultVO =  depponService.saveBudget(bo);
        if(resultVO.isResult()){
            List<DepponBudgetVO> list = JSON.parseArray(resultVO.getResponseParam().toString(), DepponBudgetVO.class);
            if(list != null && list.size() > 0){
                for(DepponBudgetVO vo : list){
                    if("RCP".equals(vo.getOmsProductCode()) || "NZBRH".equals(vo.getOmsProductCode()) || "PACKAGE".equals(vo.getOmsProductCode())
                            || "JZKH".equals(vo.getOmsProductCode())){
                        vo.setOldTotalfee(vo.getTotalfee());
                        BigDecimal fee = vo.getTotalfee().multiply(BigDecimal.valueOf(0.7)).setScale(0, BigDecimal.ROUND_HALF_UP);
                        vo.setTotalfee(fee);
                    }
                }
            }
            resultVO.setResponseParam(list);
            return new Result(resultVO.getResponseParam());
        } else {
            return new Result(CodeEnum.FAIL, resultVO.getReason());
        }
    }

    @Override
    @Transactional
    public Result saveSync(Long id) {
        LogisticsOrderDTO orderDTO = this.selectById(id);
        if(orderDTO == null){
            return new Result(CodeEnum.FAIL_100002);
        }

        DepponQueryOrderBO bo = new DepponQueryOrderBO();
        bo.setLogisticID(orderDTO.getLogisticId());
        DepponResultVO<DepponQueryOrderVO> resultVO = this.depponService.queryOrderList(bo);

        if(resultVO == null){
            return new Result(CodeEnum.FAIL_DEPPON_400001);
        }

        if(!resultVO.isResult()){
            if("1002".equals(resultVO.getResultCode())){
                saveCancel(id,resultVO.getReason());
            }
            return new Result(CodeEnum.FAIL.getCode(), resultVO.getReason());
        }

        LogisticsOrderDTO newOrderDTO = new LogisticsOrderDTO();
        LogisticsOrderRemarkDTO remarkDTO = new LogisticsOrderRemarkDTO();
        newOrderDTO.setId(orderDTO.getId());
        remarkDTO.setId(orderDTO.getId());

        DepponQueryOrderVO orderVO = JSONObject.parseObject(JSON.toJSONString(resultVO.getResponseParam()), DepponQueryOrderVO.class);
        newOrderDTO.setMailNo(orderVO.getMailNo());
        //发货人信息", required = true)
        DepponContactsBO sender = orderVO.getSender();
        newOrderDTO.setSenderName(sender.getName());
        remarkDTO.setSenderBusinessNetworkNo(sender.getBusinessNetworkNo());
        remarkDTO.setSenderMobile(sender.getMobile());
        remarkDTO.setSenderPhone(sender.getPhone());
        remarkDTO.setSenderProvince(sender.getProvince());
        remarkDTO.setSenderCity(sender.getCity());
        remarkDTO.setSenderCounty(sender.getCounty());
        remarkDTO.setSenderTown(sender.getTown());
        remarkDTO.setSenderAddress(sender.getAddress());

        //收货人信息", required = true)
        DepponContactsBO receiver = orderVO.getReceiver();
        newOrderDTO.setReceiverName(receiver.getName());
        remarkDTO.setReceiverToNetworkNo(receiver.getToNetworkNo());
        remarkDTO.setReceiverPhone(receiver.getPhone());
        remarkDTO.setReceiverMobile(receiver.getMobile());
        remarkDTO.setReceiverProvince(receiver.getProvince());
        remarkDTO.setReceiverCity(receiver.getCity());
        remarkDTO.setReceiverCounty(receiver.getCounty());
        remarkDTO.setReceiverTown(receiver.getTown());
        remarkDTO.setReceiverAddress(receiver.getAddress());
        remarkDTO.setReceiverCompanyName(receiver.getCompanyName());

        //货物名称", required = true)
        remarkDTO.setCargoName(orderVO.getCargoName());
        //总件数（包裹数）", required = true)
        remarkDTO.setTotalNumber(orderVO.getTotalNumber());
        //总重量单位：kg", required = true)
        remarkDTO.setTotalWeight(orderVO.getTotalWeight());
        //总体积单位：m3")
        remarkDTO.setTotalVolume(orderVO.getTotalVolume());

        //支付方式", required = true)
        newOrderDTO.setPayType(orderVO.getPayType());//：0、发货人付款（现付）（大客户模式不支持寄付） 1、收货人付款（到付） 2、发货人付款（月结）
        //保价金额：单位：元")
        remarkDTO.setInsuranceValue(orderVO.getInsuranceValue());
        //代收货款类型：0：无代收 1：即日退 3：三日退 代收货款金额不为0时，此项客户必填，代收货款金额为0或为空，则代收类型默认为无")
        remarkDTO.setCodType(orderVO.getCodType());
        //代收货款金额：可为空 如为空，则FOSS开单时默认为0，单位：元")
        remarkDTO.setCodValue(orderVO.getCodValue());
        //代收货款费：可为空 如为空，则FOSS开单时默认为0，单位：元")
        remarkDTO.setCodPrice(orderVO.getCodPrice());
        //上门接货: 是:Y 否：N")
        remarkDTO.setVistReceive(orderVO.getVistReceive());
        //送货方式: 1、自提； 2、送货进仓； 3、送货（不含上楼）； 4、送货上楼； 5、大件上楼", required = true)
        remarkDTO.setDeliveryType(orderVO.getDeliveryType());
        //签收回单：", required = true)
        remarkDTO.setBackSignBill(orderVO.getBackSignBill());//0:无需返单 1：签收单原件返回 2:电子签收单（电子签名图片需要另外对接查询接口）
        //包装（直接用中文） ： 纸、纤、木箱、木架、托膜、托木（大客户模式下运输方式为零担时必填）")
        remarkDTO.setPackageService(orderVO.getPackageService());
        //短信通知：Y：需要 N: 不需要")
        remarkDTO.setSmsNotify(orderVO.getSmsNotify());
        //备注")
        remarkDTO.setRemark(orderVO.getRemark());

        //运费：单位：元")
        remarkDTO.setTransportPrice(orderVO.getTransportPrice());
        //总价格：单位：元")
        newOrderDTO.setTotalPrice(orderVO.getTotalPrice());
        //上门接货费：单位：元")
        remarkDTO.setVistReceivePrice(orderVO.getVistReceivePrice());
        //送货费：单位：元")
        remarkDTO.setDeliveryPrice(orderVO.getDeliveryPrice());
        //签回收单费：单位：元")
        remarkDTO.setBackSignBillPrice(orderVO.getBackSignBillPrice());
        //包装费用：单位：元")
        remarkDTO.setPackageServicePrice(orderVO.getPackageServicePrice());
        //短信通知费用：单位：元")
        remarkDTO.setSmsNotifyPrice(orderVO.getSmsNotifyPrice());
        //其他费用：单位：元")
        remarkDTO.setOtherPrice(orderVO.getOtherPrice());
        //燃油附加: 是:Y 否：N")
        remarkDTO.setFuelSurcharge(orderVO.getFuelSurcharge());
        //燃油附加费")
        remarkDTO.setFuelSurchargePrice(orderVO.getFuelSurchargePrice());
        String statusType = null;
        //ACCEPT已受理，CANCEL已取消，FAILGOT揽货失败，GOBACK已退回，GOT已开单，INVALID已作废，RECEIPTING接货中，REJECT已拒绝，SHOUTCAR已约车，SIGNFAILED异常签收，SIGNSUCCESS正常签收")
        if(StrUtils.isNotEmpty(orderVO.getStatusType())){
            if("已取消".equals(orderVO.getStatusType())){
                statusType = "CANCEL";
            } else if("已受理".equals(orderVO.getStatusType())){
                statusType = "ACCEPT";
            } else if("揽货失败".equals(orderVO.getStatusType())){
                statusType = "FAILGOT";
            } else if("已退回".equals(orderVO.getStatusType())){
                statusType = "GOBACK";
            } else if("已开单".equals(orderVO.getStatusType())){
                statusType = "GOT";
            } else if("已作废".equals(orderVO.getStatusType())){
                statusType = "INVALID";
            } else if("接货中".equals(orderVO.getStatusType())){
                statusType = "RECEIPTING";
            } else if("已拒绝".equals(orderVO.getStatusType())){
                statusType = "REJECT";
            } else if("已约车".equals(orderVO.getStatusType())){
                statusType = "SHOUTCAR";
            } else if("异常签收".equals(orderVO.getStatusType())){
                statusType = "SIGNFAILED";
            } else if("正常签收".equals(orderVO.getStatusType())){
                statusType = "SIGNSUCCESS";
            } else {
                statusType = orderVO.getStatusType();
            }
        }
        newOrderDTO.setStatusType(statusType);
        //等通知发货费用：单位：元")
//        newDTO.setWaitn orderVO.getWaitNotifySendPrice();
//        //是否等通知发货")
//        remarkDTO.setorderVO.getWaitNotifySend();
        //反馈原因")
        newOrderDTO.setComments(orderVO.getComments());
        //会员类型")
        remarkDTO.setMemberType(orderVO.getMemberType());
        //保价费：单位：元")
        remarkDTO.setInsurancePrice(orderVO.getInsurancePrice());

        //月结账单金额计算
        if(orderDTO.getType() == 1 && orderDTO.getShopId().longValue() > 0){
            savePayMoney(newOrderDTO, orderDTO);
            if("CANCEL".equals(newOrderDTO.getStatusType()) || "FAILGOT".equals(newOrderDTO.getStatusType()) || "INVALID".equals(newOrderDTO.getStatusType())){
                saveCancleMoney(newOrderDTO, orderDTO);
            }
        }

        this.updateById(newOrderDTO);
        this.logisticsOrderRemarkMapper.updateById(remarkDTO);
        return new Result();
    }

    @Override
    public Result saveSyncBusiness(Long id) {
        LogisticsOrderDTO dto = this.selectById(id);
        if(dto == null){
            return new Result(CodeEnum.FAIL_100002);
        }

        updateMailNo(dto.getLogisticId(), dto.getMailNo(), CodeEnum.FAIL_100008);
        return new Result();
    }

    /**
     * 通知回调
     * @param bo
     */
    @Override
    @Transactional
    public void saveDoNotify(DepponPushOrderBO bo) {
        Wrapper wrapper = new EntityWrapper();
        wrapper.eq("logistic_id", bo.getLogisticID());
        LogisticsOrderDTO orderDTO = this.selectOne(wrapper);
        if(orderDTO == null){
            throw new ServiceException(CodeEnum.FAIL_DEPPON_400006);
        } else {
            LogisticsOrderDTO newOrderDTO = new LogisticsOrderDTO();
            LogisticsOrderRemarkDTO newRemarkDTO = new LogisticsOrderRemarkDTO();
            newOrderDTO.setId(orderDTO.getId());
            newRemarkDTO.setId(orderDTO.getId());
            //渠道单号", required = true)
            //运单号", required = true)
            newOrderDTO.setMailNo(bo.getMailNo());
            //状态更新时间", required = true)
            newOrderDTO.setGmtUpdated(bo.getGmtUpdated());
            //ACCEPT已受理，CANCEL已取消，FAILGOT揽货失败，GOBACK已退回，GOT已开单，INVALID已作废，RECEIPTING接货中，REJECT已拒绝，SHOUTCAR已约车，SIGNFAILED异常签收，SIGNSUCCESS正常签收")
            newOrderDTO.setStatusType(bo.getStatusType());
            //反馈原因")
            newOrderDTO.setComments(bo.getComments());
            //发货部门编码")
            newRemarkDTO.setSenderBusinessNetworkNo(bo.getBusinessNetworkNo());
            //到达部门编码：德邦营业部门编码，若没有同步德邦营业部门数据，可以不填")
            newRemarkDTO.setReceiverToNetworkNo(bo.getToNetworkNo());

            //发货人信息", required = true)
            DepponContactsBO sender = bo.getSender();
            if(sender != null){
                //发货人名称")
                newOrderDTO.setSenderName(sender.getName());
                //发货人公司")
                newRemarkDTO.setSenderCompanyName(sender.getCompanyName());
                //发货部门编码")
                newRemarkDTO.setSenderBusinessNetworkNo(sender.getBusinessNetworkNo());
                //发货人手机")
                newRemarkDTO.setSenderMobile(sender.getMobile());
                //发货人电话")
                newRemarkDTO.setSenderPhone(sender.getPhone());
                //发货人省份")
                newRemarkDTO.setSenderProvince(sender.getProvince());
                //发货人城市")
                newRemarkDTO.setSenderCity(sender.getCity());
                //发货人区县")
                newRemarkDTO.setSenderCounty(sender.getCounty());
                //发货人乡镇街道")
                newRemarkDTO.setSenderTown(sender.getTown());
                //发货人详细地址")
                newRemarkDTO.setSenderAddress(sender.getAddress());
            }


            //收货人信息", required = true)
            DepponContactsBO receiver = bo.getReceiver();

            if(receiver != null){
                //收货人名称")
                newOrderDTO.setReceiverName(receiver.getName());
                //到达部门编码：德邦营业部门编码，若没有同步德邦营业部门数据，可以不填")
                newRemarkDTO.setReceiverToNetworkNo(receiver.getToNetworkNo());
                //收货人电话")
                newRemarkDTO.setReceiverPhone(receiver.getPhone());
                //收货人手机")
                newRemarkDTO.setReceiverMobile(receiver.getMobile());
                //收货人省份")
                newRemarkDTO.setReceiverProvince(receiver.getProvince());
                //收货人城市")
                newRemarkDTO.setReceiverCity(receiver.getCity());
                //收货人区县")
                newRemarkDTO.setReceiverCounty(receiver.getCounty());
                //收货人镇街道")
                newRemarkDTO.setReceiverTown(receiver.getTown());
                //收货人详细地址")
                newRemarkDTO.setReceiverAddress(receiver.getAddress());
                //收货人公司")
                newRemarkDTO.setReceiverCompanyName(receiver.getCompanyName());
            }


            //货物名称", required = true)
            newRemarkDTO.setCargoName(bo.getCargoName());
            //总件数（包裹数）", required = true)
            newRemarkDTO.setTotalNumber(bo.getTotalNumber());
            //总重量单位：kg", required = true)
            newRemarkDTO.setTotalWeight(bo.getTotalWeight());
            //总体积单位：m3")
            newRemarkDTO.setTotalVolume(bo.getTotalVolume());
            //总价格：单位：元")
            newOrderDTO.setTotalPrice(bo.getTotalPrice());

            //支付方式", required = true)
            newOrderDTO.setPayType(bo.getPayType());//：0、发货人付款（现付）（大客户模式不支持寄付） 1、收货人付款（到付） 2、发货人付款（月结）
            //运输方式/产品类型", required = true)
            newRemarkDTO.setTransportType(bo.getTransportType());//（具体传值请与月结合同签订约定的为准，否则可能影响计费） 快递运输方式 : RCP：大件快递360； NZBRH：重包入户； ZBTH：重包特惠； WXJTH：微小件特惠； JJDJ：经济大件； PACKAGE：标准快递；HKDJC：航空大件次日达; HKDJG：航空大件隔日达; TZKJC：特快专递; 零担运输方式： JZKY：精准空运（仅散客模式支持该运输方式）; JZQY_LONG：精准汽运； JZKH：精准卡航； 整车运输方式 1.整车配送 ZCPS 2.精准专车 JZZHC

            //运费：单位：元")
            newRemarkDTO.setTransportPrice(bo.getTransportPrice());
            //保价金额：单位：元")
            newRemarkDTO.setInsuranceValue(bo.getInsuranceValue());
            //保价费：单位：元")
            newRemarkDTO.setInsurancePrice(bo.getInsurancePrice());

            //代收货款类型：0：无代收 1：即日退 3：三日退 代收货款金额不为0时，此项客户必填，代收货款金额为0或为空，则代收类型默认为无")
            newRemarkDTO.setCodType(bo.getCodType());
            //代收货款金额：可为空 如为空，则FOSS开单时默认为0，单位：元")
            newRemarkDTO.setCodValue(bo.getCodValue());
            //代收货款费：可为空 如为空，则FOSS开单时默认为0，单位：元")
            newRemarkDTO.setCodPrice(bo.getCodPrice());

            //上门接货: 是:Y 否：N")
            newRemarkDTO.setVistReceive(bo.getVistReceive());
            //上门接货费：单位：元")
            newRemarkDTO.setVistReceivePrice(bo.getVistReceivePrice());

            //送货方式: 1、自提； 2、送货进仓； 3、送货（不含上楼）； 4、送货上楼； 5、大件上楼", required = true)
            newRemarkDTO.setDeliveryType(bo.getDeliveryType());
            //送货费：单位：元")
            newRemarkDTO.setDeliveryPrice(bo.getDeliveryPrice());


            //签收回单：", required = true)
            newRemarkDTO.setBackSignBill(bo.getBackSignBill());//0:无需返单 1：签收单原件返回 2:电子签收单（电子签名图片需要另外对接查询接口）
            //签回收单费：单位：元")
            newRemarkDTO.setBackSignBillPrice(bo.getBackSignBillPrice());

            //包装（直接用中文） ： 纸、纤、木箱、木架、托膜、托木（大客户模式下运输方式为零担时必填）")
            newRemarkDTO.setPackageService(bo.getPackageService());
            //包装费用：单位：元")
            newRemarkDTO.setPackageServicePrice(bo.getPackageServicePrice());

            //其他费用：单位：元")
            newRemarkDTO.setOtherPrice(bo.getOtherPrice());

            //月结账单金额计算
            if(orderDTO.getType() == 1 && orderDTO.getShopId().longValue() > 0){
                savePayMoney(newOrderDTO, orderDTO);
                if("CANCEL".equals(newOrderDTO.getStatusType()) || "FAILGOT".equals(newOrderDTO.getStatusType()) || "INVALID".equals(newOrderDTO.getStatusType())){
                    saveCancleMoney(newOrderDTO, orderDTO);
                }
            }
            wrapper = new EntityWrapper();
            //ACCEPT已受理，CANCEL已取消，FAILGOT揽货失败，GOBACK已退回，GOT已开单，INVALID已作废，RECEIPTING接货中，REJECT已拒绝，SHOUTCAR已约车，SIGNFAILED异常签收，SIGNSUCCESS正常签收
            wrapper.eq("logistic_id", bo.getLogisticID());
            String[] s = {"CANCEL", "FAILGOT", "INVALID", "REJECT", "SIGNFAILED", "SIGNSUCCESS"};
            wrapper.ne("status_type", s);

            if(!this.update(newOrderDTO, wrapper)){
                throw new ServiceException(CodeEnum.FAIL_DEPPON_400008);
            }

            newRemarkDTO.setUpdateTime(new Date());
            this.logisticsOrderRemarkMapper.updateById(newRemarkDTO);
        }
    }

    @Override
    public LogisticsOrderDTO getByMailNo(String mailNo) {
        Wrapper wrapper = new EntityWrapper();
        wrapper.eq("mail_no", mailNo);
        return this.selectOne(wrapper);
    }

    @Override
    public boolean updateBillMoney(Long id, BigDecimal money) {
        Integer flag = this.baseMapper.updateBillMoney(id, money);
        if(flag != null && flag == 1){
            return true;
        }
        return false;
    }

    private void savePayMoney(LogisticsOrderDTO newOrderDTO, LogisticsOrderDTO orderDTO){
        if(orderDTO.getTotalPriceStatus() == 0){
            log.error("------2----"+(newOrderDTO.getTotalPrice() != null && newOrderDTO.getTotalPrice().compareTo(BigDecimal.ZERO) > 0));
            log.error("------3----"+(newOrderDTO.getTotalPrice()));
            if(newOrderDTO.getTotalPrice() != null && newOrderDTO.getTotalPrice().compareTo(BigDecimal.ZERO) > 0){
                log.error("------4----");
                BigDecimal money = orderDTO.getTotalBudgetPrice().subtract(newOrderDTO.getTotalPrice());
                LogisticsUserDTO userDTO = logisticsUserService.selectById(orderDTO.getShopId());
                //添加一条日志
                logisticsUserMoneyLogService.insert(orderDTO.getId(), orderDTO.getShopId(), 6, newOrderDTO.getTotalPrice(),  userDTO.getMguaranteeMoneyQuota(), userDTO.getMguaranteeMoney(), userDTO.getLogisticsMoneyQuota(), userDTO.getLogisticsMoneyUsed(), userDTO.getLogisticsMoneyUnused(), userDTO.getLogisticsMoneyUsedScale(), orderDTO.getCreateUserId(), userDTO.getCreateUserName(), CodeEnum.FAIL_100008);
                if(money.compareTo(BigDecimal.ZERO) < 0){//继续扣金额
                    log.error("------5----"+ money);
                    LogisticsUserDTO newUserDTO = new LogisticsUserDTO();

                    BigDecimal moneyUsed = userDTO.getLogisticsMoneyUsed().add(money.negate());
                    if(moneyUsed.compareTo(BigDecimal.ZERO) < 0 || moneyUsed.compareTo(userDTO.getLogisticsMoneyQuota()) > 0){
                        throw new ServiceException(CodeEnum.FAIL_DEPPON_400003);
                    }
                    newUserDTO.setLogisticsMoneyUsed(moneyUsed);
                    newUserDTO.setLogisticsMoneyUnused(userDTO.getLogisticsMoneyQuota().subtract(newUserDTO.getLogisticsMoneyUsed()));
                    newUserDTO.setLogisticsMoneyUsedScale(newUserDTO.getLogisticsMoneyUsed().divide(userDTO.getLogisticsMoneyQuota(), 4, BigDecimal.ROUND_HALF_UP).multiply(BigDecimal.valueOf(100)));
                    logisticsUserService.updateMoney(orderDTO.getId(), newUserDTO, userDTO, money, 5, orderDTO.getCreateUserId(), orderDTO.getCreateUserName());

                } else {//返还金额
                    log.error("------6----"+ money);
                    LogisticsUserDTO newUserDTO = new LogisticsUserDTO();
                    BigDecimal moneyUsed = userDTO.getLogisticsMoneyUsed().subtract(money);
                    if(moneyUsed.compareTo(BigDecimal.ZERO) < 0){
                        throw new ServiceException(CodeEnum.FAIL_DEPPON_400003);
                    }
                    newUserDTO.setLogisticsMoneyUsed(moneyUsed);
                    newUserDTO.setLogisticsMoneyUnused(userDTO.getLogisticsMoneyQuota().subtract(newUserDTO.getLogisticsMoneyUsed()));
                    newUserDTO.setLogisticsMoneyUsedScale(newUserDTO.getLogisticsMoneyUsed().divide(userDTO.getLogisticsMoneyQuota(), 4, BigDecimal.ROUND_HALF_UP).multiply(BigDecimal.valueOf(100)));
                    logisticsUserService.updateMoney(orderDTO.getId(), newUserDTO, userDTO, money, 8, orderDTO.getCreateUserId(), orderDTO.getCreateUserName());
                }

                newOrderDTO.setTotalPriceStatus(1);
            }
        } else {
            //ACCEPT已受理，CANCEL已取消，FAILGOT揽货失败，GOBACK已退回，GOT已开单，INVALID已作废，RECEIPTING接货中，REJECT已拒绝，SHOUTCAR已约车，SIGNFAILED异常签收，SIGNSUCCESS正常签收")
            if("SIGNFAILED".equals(newOrderDTO.getStatusType()) || "SIGNSUCCESS".equals(newOrderDTO.getStatusType())){
                if(orderDTO.getTotalPrice().compareTo(newOrderDTO.getTotalPrice()) != 0){
                    BigDecimal money = orderDTO.getTotalPrice().subtract(newOrderDTO.getTotalPrice());
                    LogisticsUserDTO userDTO = logisticsUserService.selectById(orderDTO.getShopId());
                    //添加一条日志
                    logisticsUserMoneyLogService.insert(orderDTO.getId(), orderDTO.getShopId(), 6, newOrderDTO.getTotalPrice(),  userDTO.getMguaranteeMoneyQuota(), userDTO.getMguaranteeMoney(), userDTO.getLogisticsMoneyQuota(), userDTO.getLogisticsMoneyUsed(), userDTO.getLogisticsMoneyUnused(), userDTO.getLogisticsMoneyUsedScale(), orderDTO.getCreateUserId(), userDTO.getCreateUserName(), CodeEnum.FAIL_100008);
                    if(money.compareTo(BigDecimal.ZERO) < 0){//继续扣金额
                        log.error("------5----"+ money);
                        LogisticsUserDTO newUserDTO = new LogisticsUserDTO();

                        BigDecimal moneyUsed = userDTO.getLogisticsMoneyUsed().add(money.negate());
                        if(moneyUsed.compareTo(BigDecimal.ZERO) < 0 || moneyUsed.compareTo(userDTO.getLogisticsMoneyQuota()) > 0){
                            throw new ServiceException(CodeEnum.FAIL_DEPPON_400003);
                        }
                        newUserDTO.setLogisticsMoneyUsed(moneyUsed);
                        newUserDTO.setLogisticsMoneyUnused(userDTO.getLogisticsMoneyQuota().subtract(newUserDTO.getLogisticsMoneyUsed()));
                        newUserDTO.setLogisticsMoneyUsedScale(newUserDTO.getLogisticsMoneyUsed().divide(userDTO.getLogisticsMoneyQuota(), 4, BigDecimal.ROUND_HALF_UP).multiply(BigDecimal.valueOf(100)));
                        logisticsUserService.updateMoney(orderDTO.getId(), newUserDTO, userDTO, money, 5, orderDTO.getCreateUserId(), orderDTO.getCreateUserName());

                    } else {//返还金额
                        log.error("------6----"+ money);
                        LogisticsUserDTO newUserDTO = new LogisticsUserDTO();
                        BigDecimal moneyUsed = userDTO.getLogisticsMoneyUsed().subtract(money);
                        if(moneyUsed.compareTo(BigDecimal.ZERO) < 0){
                            throw new ServiceException(CodeEnum.FAIL_DEPPON_400003);
                        }
                        newUserDTO.setLogisticsMoneyUsed(moneyUsed);
                        newUserDTO.setLogisticsMoneyUnused(userDTO.getLogisticsMoneyQuota().subtract(newUserDTO.getLogisticsMoneyUsed()));
                        newUserDTO.setLogisticsMoneyUsedScale(newUserDTO.getLogisticsMoneyUsed().divide(userDTO.getLogisticsMoneyQuota(), 4, BigDecimal.ROUND_HALF_UP).multiply(BigDecimal.valueOf(100)));
                        logisticsUserService.updateMoney(orderDTO.getId(), newUserDTO, userDTO, money, 8, orderDTO.getCreateUserId(), orderDTO.getCreateUserName());
                    }
                }
            }
        }
    }

    /**
     * 撤销订单退款金额
     * @param newOrderDTO
     * @param orderDTO
     */
    private void saveCancleMoney(LogisticsOrderDTO newOrderDTO, LogisticsOrderDTO orderDTO){
        if(newOrderDTO.getTotalPrice() == null){
            newOrderDTO.setTotalPrice(orderDTO.getTotalPrice());
        }
        if(newOrderDTO.getTotalPrice().compareTo(BigDecimal.ZERO) > 0 && orderDTO.getTotalPriceStatus() == 1){
            LogisticsUserDTO userDTO = logisticsUserService.selectById(orderDTO.getShopId());
            LogisticsUserDTO newUserDTO = new LogisticsUserDTO();
            BigDecimal moneyUsed = userDTO.getLogisticsMoneyUsed().subtract(orderDTO.getTotalPrice());
            if(moneyUsed.compareTo(BigDecimal.ZERO) < 0){
                moneyUsed = BigDecimal.ZERO;
            }
            newUserDTO.setLogisticsMoneyUsed(moneyUsed);
            newUserDTO.setLogisticsMoneyUnused(userDTO.getLogisticsMoneyQuota().subtract(newUserDTO.getLogisticsMoneyUsed()));
            newUserDTO.setLogisticsMoneyUsedScale(newUserDTO.getLogisticsMoneyUsed().divide(userDTO.getLogisticsMoneyQuota(), 4, BigDecimal.ROUND_HALF_UP).multiply(BigDecimal.valueOf(100)));
            logisticsUserService.updateMoney(orderDTO.getId(), newUserDTO, userDTO, newOrderDTO.getTotalPrice(), 8, orderDTO.getCreateUserId(), orderDTO.getCreateUserName());
            newOrderDTO.setTotalPriceStatus(2);
        } else {
            if(orderDTO.getTotalBudgetPrice().compareTo(BigDecimal.ZERO) > 0 && orderDTO.getTotalPriceStatus() != 2){
                LogisticsUserDTO userDTO = logisticsUserService.selectById(orderDTO.getShopId());
                LogisticsUserDTO newUserDTO = new LogisticsUserDTO();
                BigDecimal moneyUsed = userDTO.getLogisticsMoneyUsed().subtract(orderDTO.getTotalBudgetPrice());
                if(moneyUsed.compareTo(BigDecimal.ZERO) < 0){
                    moneyUsed = BigDecimal.ZERO;
                }
                newUserDTO.setLogisticsMoneyUsed(moneyUsed);
                newUserDTO.setLogisticsMoneyUnused(userDTO.getLogisticsMoneyQuota().subtract(newUserDTO.getLogisticsMoneyUsed()));
                newUserDTO.setLogisticsMoneyUsedScale(newUserDTO.getLogisticsMoneyUsed().divide(userDTO.getLogisticsMoneyQuota(), 4, BigDecimal.ROUND_HALF_UP).multiply(BigDecimal.valueOf(100)));
                logisticsUserService.updateMoney(orderDTO.getId(), newUserDTO, userDTO, orderDTO.getTotalBudgetPrice().negate(), 8, orderDTO.getCreateUserId(), orderDTO.getCreateUserName());
                newOrderDTO.setTotalPriceStatus(2);
            }
        }
    }
}
